import React, { useEffect } from 'react';
import { Form, Select, Input, Button } from 'antd';



interface FormItemOption {
  value: string | number; // 选项的值
  label: string; // 选项的显示文本
}

interface FormItemConfig {
  name: string; // 表单项的名称
  label: string;      // 表单项的标签
  type?: 'input' | 'select'; // 表单项的类型，默认为input
  required?: boolean; // 表单项是否必填，默认为false
  options?: FormItemOption[]; // 表单项的选项，仅在type为select时有效
}

interface ModalFormProps {
  formItems: FormItemConfig[];
  handleCancel: () => void;
  formParams: any;
}

const ModalForm: React.FC<ModalFormProps> = (props) => {
  const [form] = Form.useForm();
  const formItems = props.formItems; // 表单项配置
  // 提交表单（验证+回调）
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      console.log('表单数据：', values);
      
      // 如果有提交回调，调用它
      if (props.formParams?.onSubmit) {
        await props.formParams.onSubmit(values);
      }
      
      form.resetFields(); // 可选：提交后重置表单
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  useEffect(() => {
    console.log(props.formParams, '回显数据');
    
    // 如果有初始值，设置到表单中
    if (props.formParams?.initialValues) {
      form.setFieldsValue(props.formParams.initialValues);
    }
  }, [props.formParams, form]);
  return (
    <Form
      form={form}
      layout="vertical"
    >
      {/* 编号（固定为“系统自动生成”，只读） */}
      <Form.Item name="code" label="编号">
        <Input placeholder="系统自动生成" readOnly />
      </Form.Item>

      {/* 动态渲染表单项 */}
      {formItems.map(item => (
        <Form.Item
          key={item.name}
          name={item.name}
          label={item.label}
          rules={item.required ? [{ required: true, message: `请输入${item.label}` }] : []}
        >
          {item.type === 'select' ? (
            <Select placeholder={item.label}>
              {item.options?.map(opt => (
                <Select.Option key={opt.value} value={opt.value}>{opt.label}</Select.Option>
              ))}
            </Select>
          ) : (
            <Input placeholder={item.label} />
          )}
        </Form.Item>
      ))}

      {/* 备注（固定表单项） */}
      <Form.Item name="remark" label="备注">
        <Input placeholder="备注内容" />
      </Form.Item>

      {/* 按钮区域 */}
      <Form.Item>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
          <Button onClick={props.handleCancel}>
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            确定
          </Button>
        </div>
      </Form.Item>
    </Form>
  );
};

export default ModalForm;